package com.weichai.app.page.home.view;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.weichai.app.R;
import com.weichai.app.arch.base.BaseFragment;
import com.weichai.app.arch.config.RouterParams;
import com.weichai.app.arch.utils.GpsUtil;
import com.weichai.app.arch.utils.StringUtil;
import com.weichai.app.bean.ServiceStationEntity;
import com.weichai.app.databinding.FragmentServiceStationBinding;
import com.weichai.app.page.home.adapter.ServiceStationAdapter;
import com.weichai.app.page.home.dialog.CancelConfirmPopup;
import com.weichai.app.page.home.viewmodel.ServiceStationVM;
import com.weichai.app.page.main.MainModel;

import java.util.ArrayList;
import java.util.List;

import dev.utils.app.AppUtils;
import dev.utils.app.ScreenUtils;
import dev.utils.app.SizeUtils;

/**
 * 服务站
 */
public class ServiceStationFragment extends BaseFragment<FragmentServiceStationBinding, ServiceStationVM> {
    private BaiduMap baiduMap;
    private TextureMapView mapView;
    private LocationClient mLocationClient;
    private List<LatLng> latLngList = new ArrayList<>();
    private GpsUtil gpsUtil;
    private BottomSheetBehavior<LinearLayout> bottomSheetBehavior;

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        if (null != gpsUtil) {
            gpsUtil.onDestroy();
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        mLocationClient.stop();
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();
    }

    @Override
    protected void initView() {
        bottomSheetBehavior = BottomSheetBehavior.from(mViewBinding.llBottomSheetBehavior);
        bottomSheetBehavior.setPeekHeight((int) (ScreenUtils.getScreenHeight() * 0.5));
        bottomSheetBehavior.setHideable(true);
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState != BottomSheetBehavior.STATE_EXPANDED) {
                    ViewGroup.LayoutParams layoutParams = bottomSheet.getLayoutParams();
                    layoutParams.height = (int) (ScreenUtils.getScreenHeight() * 0.8);
                    bottomSheet.setLayoutParams(layoutParams);
                }
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    mViewBinding.clBottom.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });

        mViewBinding.clBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                mViewBinding.clBottom.setVisibility(View.GONE);
            }
        });

        gpsUtil = new GpsUtil(mActivity);
        gpsUtil.setGPSInterface(new GpsUtil.GPSInterface() {
            @Override
            public void gpsSwitchState(boolean gpsOpen) {
                if (gpsOpen) {
                    mViewBinding.clLocationOff.setVisibility(View.GONE);
                } else {
                    mViewBinding.clLocationOff.setVisibility(View.VISIBLE);
                }
            }
        });
        if (!GpsUtil.gpsIsOpen(mActivity)) {
            mViewBinding.clLocationOff.setVisibility(View.VISIBLE);
        }
        mViewBinding.tvOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                AppUtils.startActivity(intent);
            }
        });
        mViewBinding.ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewBinding.clLocationOff.setVisibility(View.GONE);
            }
        });

        mViewBinding.ivBottomPosition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GpsUtil.gpsIsOpen(mActivity)) {
                    // 开始定位
                } else {
                    // 弹框
                    CancelConfirmPopup cancelConfirmPopup = new CancelConfirmPopup(mActivity);
                    cancelConfirmPopup.showAlert(new CancelConfirmPopup.AlertHint("定位服务未开启", "请在设置中开启定位设置", "暂不",
                            "去设置", true, new CancelConfirmPopup.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            AppUtils.startActivity(intent);
                        }

                        @Override
                        public void onCancel() {

                        }
                    }));
                }
            }
        });

        mViewBinding.ivPosition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GpsUtil.gpsIsOpen(mActivity)) {
                    // 开始定位
                } else {
                    // 弹框
                    CancelConfirmPopup cancelConfirmPopup = new CancelConfirmPopup(mActivity);
                    cancelConfirmPopup.showAlert(new CancelConfirmPopup.AlertHint("定位服务未开启", "请在设置中开启定位设置", "暂不",
                            "去设置", true, new CancelConfirmPopup.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            AppUtils.startActivity(intent);
                        }

                        @Override
                        public void onCancel() {

                        }
                    }));
                }
            }
        });

        mViewBinding.etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    mViewModel.searchContent.setValue(s.toString());
                    mViewModel.search();
                }
            }
        });
        mViewBinding.clTitleBar.setPadding(SizeUtils.dipConvertPx(16),
                mViewBinding.clTitleBar.getTop() + ScreenUtils.getStatusBarHeight() +
                        SizeUtils.dipConvertPx(2),
                SizeUtils.dipConvertPx(16), SizeUtils.dipConvertPx(2));
        mapView = mViewBinding.mapView;
        baiduMap = mViewBinding.mapView.getMap();
        mViewBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popPage();
            }
        });

        ServiceStationAdapter serviceStationAdapter = new ServiceStationAdapter();
        mViewBinding.rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mViewBinding.rv.addItemDecoration(new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL));
        mViewBinding.rv.setAdapter(serviceStationAdapter);

        serviceStationAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ServiceStationEntity serviceStationEntity = (ServiceStationEntity) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putParcelable("serviceStationEntity", serviceStationEntity);
                navigate(new RouterParams(R.id.stationDetailsFragment, bundle));
            }
        });

        serviceStationAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                ServiceStationEntity serviceStationEntity = (ServiceStationEntity) adapter.getData().get(position);
                StringUtil.callPhone(serviceStationEntity.sitePhone);
            }
        });

        baiduMap.setMyLocationEnabled(true);
        MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,
                true, BitmapDescriptorFactory.fromResource(R.mipmap.ic_current_location_marker));
        baiduMap.setMyLocationConfiguration(myLocationConfiguration);

        mViewModel.serviceStationList.observe(this, serviceStationList -> {
            for (ServiceStationEntity serviceStationEntity : serviceStationList) {
                //定义Maker坐标点
                LatLng point = new LatLng(Double.parseDouble(serviceStationEntity.dimension),
                        Double.parseDouble(serviceStationEntity.longitude));
                latLngList.add(point);
//构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.mipmap.ic_service_station_marker_normal);

                BitmapDescriptor bitmapSelect = BitmapDescriptorFactory
                        .fromResource(R.mipmap.ic_service_station_marker_selected);
//构建MarkerOption，用于在地图上添加Marker
                Bundle bundle = new Bundle();
                bundle.putParcelable("serviceStationEntity", serviceStationEntity);
                OverlayOptions overlayOptions = new MarkerOptions()
                        .position(point)
                        .perspective(true)
                        .extraInfo(bundle)
                        .icon(bitmap);
//在地图上添加Marker，并显示
                baiduMap.addOverlay(overlayOptions);
            }

            // 构造地理范围对象
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            // 让该地理范围包含一组地理位置坐标
            builder.include(latLngList);
            // 设置显示在指定相对于MapView的padding中的地图地理范围
            MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngBounds(builder.build(), 30, 30,
                    30, 30);
            // 更新地图
            baiduMap.setMapStatus(mapStatusUpdate);

        });

        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                navigate(new RouterParams(R.id.stationDetailsFragment, marker.getExtraInfo()));
                return true;
            }
        });

        baiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                // 设置地图中心点
                Point p = new Point(ScreenUtils.getScreenWidth() / 2, (int) (ScreenUtils.getScreenHeight() * 0.3));
                MapStatus mapStatus = new MapStatus.Builder().targetScreen(p).build();
                baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));
                // 构造地理范围对象
                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                // 让该地理范围包含一组地理位置坐标
                latLngList.add(getViewModelOfActivity(MainModel.class).locationLatLng.getValue());
                builder.include(latLngList);
                // 设置显示在指定相对于MapView的padding中的地图地理范围
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngBounds(builder.build(), 30, 30,
                        30, 30);
                // 更新地图
                baiduMap.setMapStatus(mapStatusUpdate);
            }
        });

        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                mViewBinding.clBottom.setVisibility(View.VISIBLE);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {

            }
        });

        //定位初始化
        mLocationClient = new LocationClient(mActivity);

//通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型

//设置locationClientOption
        mLocationClient.setLocOption(option);

//注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
        mLocationClient.start();
    }

    @Override
    protected void initData() {
        try {
            mViewModel.dimension.setValue(String.valueOf(getViewModelOfActivity(MainModel.class).locationLatLng.getValue().latitude));
            mViewModel.longitude.setValue(String.valueOf(getViewModelOfActivity(MainModel.class).locationLatLng.getValue().longitude));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mViewModel.search();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_service_station;
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }
            Log.i("位置：", location.toString());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
        }
    }
}
